<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/10/19
 * Time: 22:52
 */

namespace Home\Service;


use Think\Model;

class ScoreSheetService extends Model
{
    public function addSheetToScore($param)
    {
        $model = M('ScoreSheet');
        //判断该关系是否存在
        $map = array(
            'score_id' => $param['score_id'],
            'sheet_id' => $param['sheet_id'],
            'creator'  => $param['creator']
        );

        $res = $model->where($map)->find();
        if ($res) {
            if ($res['is_delete']) {
                $data = array('is_delete'=>0);
                $res = $model->where($map)->save($data);
                //谱单曲谱数记录+1
                M('Score')->where(array('id'=>$param['score_id']))->setInc('sheet_count');
                //曲谱收藏数+1
                M('Sheet')->where(array('id'=>$param['sheet_id']))->setInc('fav_count');
            } else {
                //曲谱已存在
                return 500;
            }
            return $res;
        } else {
            $data = $model->create($param);
            if ($data) {
                $param['create_time'] = date('Y-m-d H:i:s', time());
                $id = $model->add($param);
                if ($id) {
                    //谱单曲谱数记录+1
                    M('Score')->where(array('id'=>$param['score_id']))->setInc('sheet_count');
                    //曲谱收藏数+1
                    M('Sheet')->where(array('id'=>$param['sheet_id']))->setInc('fav_count');

                }
                return $id;
            } else {
                E($model->getError());
            }
        }
    }
}